package cn.edu.ldu.communityqa.communityqa.dao;

import cn.edu.ldu.communityqa.communityqa.entity.Answer;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class AnswerDao {

    private final JdbcTemplate jdbcTemplate;

    public AnswerDao(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public int save(Answer answer) {
        String sql = "INSERT INTO answer (question_id, user_id, content) VALUES (?, ?, ?)";
        return jdbcTemplate.update(
            sql,
            answer.getQuestionId(),
            answer.getUserId(),
            answer.getContent()
        );
    }

    public int update(Answer answer) {
        String sql = "UPDATE answer SET content = ? WHERE id = ?";
        return jdbcTemplate.update(
            sql,
            answer.getContent(),
            answer.getId()
        );
    }

    public int deleteById(Long id) {
        String sql = "DELETE FROM answer WHERE id = ?";
        return jdbcTemplate.update(sql, id);
    }

    public Answer findById(Long id) {
        String sql = "SELECT * FROM answer WHERE id = ?";
        return jdbcTemplate.queryForObject(sql, new AnswerRowMapper(), id);
    }

    public List<Answer> findByQuestionId(Long questionId) {
        String sql = "SELECT * FROM answer WHERE question_id = ?";
        return jdbcTemplate.query(sql, new AnswerRowMapper(), questionId);
    }

    public List<Answer> findByUserId(Long userId) {
        String sql = "SELECT * FROM answer WHERE user_id = ?";
        return jdbcTemplate.query(sql, new AnswerRowMapper(), userId);
    }

    public List<Answer> findAll() {
        String sql = "SELECT * FROM answer";
        return jdbcTemplate.query(sql, new AnswerRowMapper());
    }

    static class AnswerRowMapper implements RowMapper<Answer> {
        @Override
        public Answer mapRow(ResultSet rs, int rowNum) throws SQLException {
            Answer answer = new Answer();
            answer.setId(rs.getLong("id"));
            answer.setQuestionId(rs.getLong("question_id"));
            answer.setUserId(rs.getLong("user_id"));
            answer.setContent(rs.getString("content"));
            answer.setCreatedAt(rs.getTimestamp("created_at").toLocalDateTime());
            answer.setUpdatedAt(rs.getTimestamp("updated_at").toLocalDateTime());
            return answer;
        }
    }
}
